﻿/**
 * Created by Administrator on 2018/3/1.
 */
+function ($) {
    'use strict';
    var $current
    var Dialog = function(options) {
        this.$element = $('body')
        this.options  = options
        this.tools    = this.TOOLS()
    }

    Dialog.DEFAULTS = {
        id          : null,
        title       : 'New Dialog',
        url         : null,
        type        : 'GET',
        data        : {},
        onLoad      : null,
        beforeClose : null,
        onClose     : null
    },
        Dialog.prototype.TOOLS = function() {
            var that = this
            var tools = {
                getDefaults: function () {
                    return Dialog.DEFAULTS
                },
                S4:function() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                },
               createIndentityWindowId:function() {
                    return "UUID-" + (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
                },
                reload: function($dialog, options) {
                    var tools = this, $dialogContent = $dialog.find('.modal-body'), onLoad, data = options && options.data
                    options = options || $dialog.data('options')
                    if (options.url) {

                        $dialogContent.ajaxUrl({
                            type:options.type || 'GET',
                            url:options.url,
                            data:data || {},
                            callback:function(response) {
                                $dialog.on('click.dismiss.dialog.data-api', '[data-toggle="close_modal"]', function(e) {
                                    $dialog.modal('hide');
                                    console.log("隐藏")
                                })
                                if (onLoad) onLoad.apply(that, [$dialog])
                            }
                        });
                    }
                }
            }
            return tools
        }
    Dialog.prototype.open = function() {
        var that    = this,
            options = that.options,
            $body   = $('body'),
            datas   = $body.data('bolt.dialog'),
            data    = datas[ options.id ] ,
            $dialog = data && data.dialo,
            id      = options && options.id;
        if ($dialog) { //if the dialog id already exists
            var op = $dialog.data('options')

            that.switchDialog($dialog)

            if ($dialog.is(':hidden')) $dialog.show()

            that.tools.reload($dialog, options)

        }else { //open a new dialog

            $dialog = $('<div class="modal fade"  data-backdrop="static"> <div class="modal-center"><div class="modal-content">' +
                '<div class="modal-header"><button type="button" class="close" data-dismiss="modal">×</button>' +
                ' <h4 class="modal-title"></h4> </div> <div class="modal-body"></div>' +
                '</div></div>')
            $dialog.on('hidden.bs.modal', function () {
                $dialog.remove();
                $dialog.data('bs.modal', null);
                delete datas[options.id]
                $.CurrentDialog = $current = null
                var $dialogs  = $('body').find('.modal,.in:first'),
                    $_current = null

                if ($dialogs.length) {
                    $_current = that.$element.getMaxIndexObj($dialogs)
                    if(!$('body').hasClass("modal-open"))$('body').addClass("modal-open");
                }else{
                    delete datas.current
                }
                if ($_current && $_current.is(':visible')) {
                    $.CurrentDialog = $current = $_current
                    that.switchDialog($_current)
                }
            });
            $dialog
                .data('options', $.extend({}, options))
                .hide()
                .appendTo($body)
            if(options.modalSize){
                $dialog.find('.modal-center').addClass(options.modalSize)
            }else{
                $dialog.find('.modal-center').addClass("modal-dialog")
            }
            if(options.buttons){
                var $actions = $('<div class="modal-footer"></div>');
                $.each(options.buttons,function(index,button){

                    var $button = $('<button type="button" class="btn btn-primary">'+button.text+'</button>');
                    button.callback ;

                    if(button.callback){
                        $button.bind('click',function(){
                            (button.callback.toFunc())();
                        })
                    }
                    $actions.append( $button );
                })
                $actions.append( '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>');
                $dialog.find('.modal-content').append($actions);
            }
            $dialog.find('.modal-title').text(options.title)

            // $dialog.on('click','.close', function(e) {
            //     that.close($dialog)
            // });
            data.dialog = $dialog
            this.tools.reload($dialog, options)
            $dialog.modal('show');

        }
        $.CurrentDialog = $current = $dialog
        datas.current = options.id
    }

    Dialog.prototype.close = function(dialog) {
        var that = this, options = that.options,datas = $('body').data('bolt.dialog'), $dialog = (typeof dialog === 'string') ? datas[dialog].dialog : dialog

        if (!$dialog || !$dialog.length) {
            return
        }
        that.onClose = options.onClose ? options.onClose.toFunc() : null;
        if ( that.onClose)  that.onClose.apply(that);
        $dialog.modal('hide')

    }

    Dialog.prototype.closeCurrent = function() {
        this.close($current)
    }

    Dialog.prototype.switchDialog = function($dialog) {
        var index = $dialog.css('z-index')

        if ($current && $current == $dialog) {
            var datas  = $('body').data('bolt.dialog')

            $.CurrentDialog = $current = $dialog
            // set current to body data
            datas.current = $dialog.data('options').id
        }

        //$dialog.modal('show');
    }
    function Plugin(option) {

        var args = arguments,
            property = option,
            dialog = 'bolt.dialog',
            $body = $('body'),
            datas = $body.data(dialog) || {}

        return this.each(function () {
            var $this   = $(this),
                options = $.extend({}, Dialog.DEFAULTS, typeof option === 'object' && option),
                id      = options && options.id,
                data
            if (datas.current){
                id = datas.current
                options.id = id
                data = datas && datas[id]
                if(data){
                    if (typeof option === 'object' && option){
                        $.extend(data.options, option)
                    }
                }
                $body.data(dialog, datas)
            }
            if (typeof property === 'string' && $.isFunction(data[property])) {
                [].shift.apply(args)
                if (!args) data[property]()
                else data[property].apply(data, args)
            }
            else{

                id = Dialog.prototype.TOOLS().createIndentityWindowId();
                options.id = id;
                datas[id] = (data = new Dialog(options))
                $body.data(dialog, datas)
                data.open()
            }

        })
    }

    $.fn.dialog             = Plugin
    $.fn.dialog.Constructor = Dialog

    Bolt.dialog = function() {
        Plugin.apply($('body'), arguments)
    }


    $(document).on('click.bolt.dialog.data-api', '[data-toggle="dialog"]', function(event) {

        var $this   = $(this), href = $this.attr('href'), data = $this.data(), options = data.options
        if (options) {
            if (typeof options === 'string') options = options.toObj()
            if (typeof options === 'object')
                $.extend(data, options)

        }

        if (!data.title) data.title = $this.text()
        if (href && !data.url) data.url = href

        Plugin.call($this, data)
        event.preventDefault();
    })
}(jQuery);

